package com.lzh.farmersshop.controller.mall;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lzh.farmersshop.entity.Order;
import com.lzh.farmersshop.entity.Orderdetails;
import com.lzh.farmersshop.entity.Shoppcart;
import com.lzh.farmersshop.entity.Userinfo;
import com.lzh.farmersshop.service.OrderService;
import com.lzh.farmersshop.service.OrderdetailsService;
import com.lzh.farmersshop.service.ShoppcartService;
import com.lzh.farmersshop.util.OrderGenerator;
import com.lzh.farmersshop.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

import static com.lzh.farmersshop.util.Result.failure;

/**
 * (Order)表控制层
 *
 * @author makejava
 * @since 2024-01-04 15:41:50
 */
@Slf4j
@RestController
@RequestMapping("mall/order")
@Transactional(rollbackFor = Exception.class)
public class UserOrderController {
    /**
     * 服务对象
     */
    @Resource
    private OrderService orderService;
    @Resource
    private OrderdetailsService orderdetailsService;
    @Resource
    private ShoppcartService shoppcartService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Result selectOne(Integer id) {
        return Result.success(orderService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param data 实体对象
     * @return 新增结果
     */
    @PostMapping("submitOrder")
    public Result submitOrder(@RequestBody JSONArray data, HttpServletRequest request) {
        //获取用户信息
        if (request.getSession().getAttribute("userinfo")== null) {
            return Result.failure(401,"请先登录！！！");
        }
        Userinfo userinfo = (Userinfo) request.getSession().getAttribute("userinfo");

        //判断是否有数据
        if (data.size() <= 0) {
            return failure("请选择数据！！！");
        }

        //生成订单号
        Long orderNum = OrderGenerator.generateOrderNumber();

        //先生成订单
        Order order = new Order();
        order.setTime(new Date());
        order.setIsdelete(1);
        order.setUserid(userinfo.getId());
        order.setOrderid(orderNum);
        order.setState(1);

        BigDecimal sumprice = BigDecimal.ZERO;

        //循环数据填充到Orderdetails
        for (int i = 0; i < data.size(); i++) {
            JSONObject jsonObject = data.getJSONObject(i);
            Integer goodsid = jsonObject.getInteger("goodsId");
            Integer cartId = jsonObject.getInteger("cartId");
            Integer num = jsonObject.getInteger("num");
            String ttile = jsonObject.getString("title");
            BigDecimal price = jsonObject.getBigDecimal("price");
            BigDecimal totalprice = jsonObject.getBigDecimal("total");

            //保存订单详情
            Orderdetails orderdetails = new Orderdetails();
            orderdetails.setIsdelete(1);
            orderdetails.setGoodsid(goodsid);
            orderdetails.setOrdernum(orderNum);
            orderdetails.setNum(num);
            orderdetails.setGoodsprice(price);
            orderdetails.setGoodsname(ttile);
            orderdetails.setSumprice(totalprice);
            orderdetailsService.save(orderdetails);

            if (cartId!=null){
                //删除购物车该条数据
                Shoppcart shoppcart = new Shoppcart();
                shoppcart.setId(cartId);
                shoppcart.setIsdelete(2);
                shoppcartService.removeById(cartId);
            }

            //计算总价格
            sumprice=sumprice.add(totalprice);
        }

        //保存订单
        order.setSumprice(sumprice);
        if (orderService.save(order)){
            return Result.success("订单提交成功！！！",order.getId());
        }
        return failure("订单提交失败！！！");
    }

    /**
     * 修改数据
     *
     * @param order 实体对象
     * @return 修改结果
     */
    @PostMapping("update")
    public Result update(Order order,HttpServletRequest request) {
        //获取用户信息
        if (request.getSession().getAttribute("userinfo")== null) {
            return Result.failure(401,"请先登录！！！");
        }

        //判断order是否为空,为空直接返回
        if (order==null){
            return Result.success("订单参数不能为空！！！");
        }

        if (order.getState()==4){
            order.setShtime(new Date());
        }

        if (orderService.updateById(order)){
            return Result.success("订单修改成功！！！");
        }
        return failure("订单修改失败！！！");
    }

    /**
     * 删除数据
     *
     * @param id 主键结合
     * @return 删除结果
     */
    @PostMapping("delete")
    public Result delete(Integer id,HttpServletRequest request) {
        if (request.getSession().getAttribute("userinfo")== null) {
            return Result.failure(401,"请先登录！！！");
        }

        if (id==null){
            return Result.failure("参数不能为空！！！");
        }

        //先根据id查询定点信息
        Order byId = orderService.getById(id);
        Order order = new Order();
        order.setIsdelete(2);
        order.setId(id);

        //删除订单表
        if (orderService.removeById(order)){
            //删除订单详情
            UpdateWrapper<Orderdetails> orderdetailsUpdateWrapper = new UpdateWrapper<>();
            orderdetailsUpdateWrapper.eq("ordernum",byId.getOrderid());
            orderdetailsUpdateWrapper.set("isdelete",2);
            orderdetailsService.update(null,orderdetailsUpdateWrapper);

            return Result.success("订单删除成功！！！");
        }
        return failure("订单删除失败！！！");
    }
}

